package com.aricwang.easyprofile.place;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.aricwang.easyprofile.R;
import com.aricwang.easyprofile.contentprovider.PlaceContentProvider;
import com.aricwang.easyprofile.database.PlaceTable;

/*
 * A ListActivity subclass to list all the rules.
 */
public class PlaceListActivity extends ListActivity implements View.OnClickListener, ListView.OnItemLongClickListener {
	public static final int REQ_ADD  = 1;
	public static final int REQ_EDIT = 2;
	public static final int REQ_COPY = 3;
	
	public static final int DIALOG_WARNING = 1;
	public static final int DIALOG_ADD = 2;
	public static final int DIALOG_LONG_CLICK = 3;
	
	private CursorAdapter mAdapter;
	
	// used to pass information to dialog
	private int mId;
	
	/////////////////////////////////////////////////////////////////////////////////////////
	// Static functions
	/////////////////////////////////////////////////////////////////////////////////////////
	

	/////////////////////////////////////////////////////////////////////////////////////////
	// Override functions
	/////////////////////////////////////////////////////////////////////////////////////////

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// set the layout
		setContentView(R.layout.list);
		Button add = (Button)findViewById(R.id.btn_add);
		add.setText(getText(R.string.new_place));

		// set the onItemLongClick handler of the ListView
		ListView listView = getListView();
		listView.setOnItemLongClickListener(this);

		// get the list of profile from content provider
		try {
			Cursor cursor = getContentResolver().query(PlaceContentProvider.CONTENT_URI, 
					PlaceTable.ALL_COLUMNS, null, null, null);
			startManagingCursor(cursor);
			
			// create the cursor adapter
			mAdapter = new CursorAdapter(this, R.layout.place_list_row, cursor, PlaceTable.ALL_COLUMNS, null);
			
			// finally, set the ListAdapter
			setListAdapter(mAdapter);
		} catch (Exception e) {
			Log.e("PlaceListActivity", "Exception: " + e.toString());
		}
	}
	
	// onClick handler of interface View.OnClickListener
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.btn_add:
			showDialog(DIALOG_ADD);
			break;
		default:
			break;
		}
	}

	// onItemLongClick handler of interface ListView.OnItemLongClickListener
	public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
		PlaceListActivity activity = (PlaceListActivity)v.getContext();

		// id is the id database, save it to activity
		activity.mId = (int)id;

		activity.showDialog(PlaceListActivity.DIALOG_LONG_CLICK);
		
		// database may changed, update the adapter
		mAdapter.notifyDataSetChanged();

		// Return true to consume the click event. In this case the
		// onListItemClick listener is not called anymore.
		return true;
	}
	
	protected Dialog onCreateDialog(int id) {
	    Dialog dialog = null;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    switch(id) {
	    case DIALOG_WARNING:
            builder.setMessage(R.string.warning_place_name_empty)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	dialog.dismiss();
                    }
                });
            dialog = builder.create();
	    	break;
	    	
	    case DIALOG_ADD:
	    	LayoutInflater factory = LayoutInflater.from(this);
            final View textEntryView = factory.inflate(R.layout.dialog_edit_text, null);
            
            builder.setTitle(R.string.new_place)
                .setView(textEntryView)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	// use textEntryView to find the EditText????
                        EditText editText = (EditText)textEntryView.findViewById(R.id.edit_text);
                    	String name = editText.getText().toString();
                    	dialog.dismiss();
                    	
                    	// if name is empty, warn user
                    	if (name.length() <= 0) {
                    		PlaceListActivity.this.showDialog(PlaceListActivity.DIALOG_WARNING);
                    	} else {
	            			// start the ProfileActivity
                    		PlaceActivity.startActivity(PlaceListActivity.this, PlaceListActivity.REQ_ADD, 0, name);
                    	}
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked cancel so do some stuff */
                    	dialog.cancel();
                    }
                });
            dialog = builder.create();	
	        break;
	        
	    case DIALOG_LONG_CLICK:
	    	final String[] items = { getString(R.string.edit), getString(R.string.delete), getString(R.string.copy) };
	    	final PlaceListActivity activity = (PlaceListActivity)this;
	    	
	    	builder.setTitle(R.string.please_select)
	    		.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						String action = items[which];
						dialog.dismiss();

						if (action == getString(R.string.edit)) {
	            			// start the PlaceActivity
                    		PlaceActivity.startActivity(activity, PlaceListActivity.REQ_EDIT, activity.mId, null);
						} else if (action == getString(R.string.copy)) {
	            			// start the PlaceActivity
                    		PlaceActivity.startActivity(activity, PlaceListActivity.REQ_COPY, activity.mId, null);
						} else if (action == getString(R.string.delete)) {
							Place.deletePlace(activity, activity.mId);
						}
					}
				});
	    	dialog = builder.create();
	    	break;
	    	
	    default:
	    	break;
	    }
	    
	    return dialog;
	}
	
	protected void onPrepareDialog(int id, Dialog dialog) {
	    switch(id) {
	    case DIALOG_ADD:
            EditText editText = (EditText)dialog.findViewById(R.id.edit_text);
            editText.setText("");
	    	break;
	    default:
	    	break;
	    }
	}

	/////////////////////////////////////////////////////////////////////////////////////////
	// Private functions
	/////////////////////////////////////////////////////////////////////////////////////////
	
	
	/////////////////////////////////////////////////////////////////////////////////////////
	// Inner classes
	/////////////////////////////////////////////////////////////////////////////////////////

	/*
	 * A SimpleCursorAdapter subclass to generate the row view of the rule list.
	 */
	private class CursorAdapter extends SimpleCursorAdapter {
		
		private int mLayoutId;
		private PlaceListActivity mActivity;
		private Cursor  mCursor;
		
		public CursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
			super(context, layout, c, from, to);
						
			mActivity = (PlaceListActivity)context;
			mLayoutId = layout;
			mCursor = c;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			mCursor.moveToPosition(position);
			
			int id       = mCursor.getInt(mCursor.getColumnIndex(PlaceTable.COLUMN_ID));
			String name  = mCursor.getString(mCursor.getColumnIndex(PlaceTable.COLUMN_NAME));
			String address = mCursor.getString(mCursor.getColumnIndex(PlaceTable.COLUMN_ADDRESS));
			float latitude  = mCursor.getFloat(mCursor.getColumnIndex(PlaceTable.COLUMN_LATITUDE));
			float longitude  = mCursor.getFloat(mCursor.getColumnIndex(PlaceTable.COLUMN_LONGITUDE));
			int radius = mCursor.getInt(mCursor.getColumnIndex(PlaceTable.COLUMN_RADIUS));

			String summary = makeSummary(address, latitude, longitude, radius);
			
			View rowView;
			
			if (convertView == null) {
				LayoutInflater inflater = (LayoutInflater)mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				rowView = inflater.inflate(mLayoutId, parent, false);	
			} else {
				rowView = convertView;
			}
			
			TextView idView = (TextView) rowView.findViewById(R.id.id);
			TextView nameView = (TextView) rowView.findViewById(R.id.name);
			TextView summaryView = (TextView) rowView.findViewById(R.id.summary);

			idView.setText(Integer.toString(id));
			nameView.setText(name);
			summaryView.setText(summary);

			return rowView;
		}
		
		private String makeSummary(String address, float latitude, float longitude, int radius) 
		{
			String summary = "";
			
			summary += address + "\n";
			summary += "Lat: " + latitude + ", Long: " + longitude + "\n";
			summary += "Radius: " + radius + " meters";

			return summary;
		}
	}	

}

